package com.erainm.dw.hive.udf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.junit.Test;

import java.util.ArrayList;

/**
 * Created by erainm on 2021/9/21 4:01 下午.
 *
 * @Description TODO:解析json串，使用key
 **/
public class ParseJsonArray extends UDF {
    public ArrayList<String> evaluate(String jsonStr, String arrKey){
        if (Strings.isNullOrEmpty(jsonStr)) {
            return null;
        }
        try {
            JSONObject ob = JSON.parseObject(jsonStr);
            JSONArray jsonArray = ob.getJSONArray(arrKey);
            ArrayList<String> result = new ArrayList<>();
            for (Object o : jsonArray) {
                result.add(o.toString());
            }
            return result;
        } catch (JSONException e) {
            return null;
        }
    }

    @Test
    public void JunitJsonArray(){
        String str = "{\"id\": 5,\"ids\": [501,502,503],\"total_number\":3}";
        String key = "ids";
        ArrayList<String> evaluate = evaluate(str, key);
        System.out.println(JSON.toJSONString(evaluate));
    }
}
